package com.janko.springbootbase.designmode.singleton;

/**
 * @ClassName Singleton2LanHan
 * @Description 懒汉式(线程不安全，调用效率不高，但是能延时加载)
 * @Author janko
 * @Date 2020/12/11 11:09
 */
public class Singleton2LanHan {
    /**
     * 懒加载程序，即：在使用的时候去使用它
     * synchronized 锁同步锁
     */

    private static Singleton2LanHan instance;

    private Singleton2LanHan() {
    }

    //如果加锁 就会变慢  Synchronized 会一直自旋 尝试着去获取这个对象
    public static synchronized   Singleton2LanHan getInstance() {
        if (instance == null) {
            //当判断instance的时候，这里多线程并发的时候 会有多个实例
            try {
                Thread.sleep(1);
            }catch (InterruptedException exception){
                exception.printStackTrace();
            }
            instance = new Singleton2LanHan();
        }
        return instance;
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(Singleton2LanHan.getInstance().hashCode());
            }).start();
        }
    }
}
